//
//  Base64.m
//  RSA Example
//
//  Created by JS Lim on 1/7/14.
//  Copyright (c) 2014 JS Lim. All rights reserved.
//

#include <stdint.h>
#include <stdlib.h>
#include "js_base_64.h"

void build_decoding_table();

static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
    'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
    'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
    'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
    'w', 'x', 'y', 'z', '0', '1', '2', '3',
    '4', '5', '6', '7', '8', '9', '+', '/'};
static char *decoding_table = NULL;
static int mod_table[] = {0, 2, 1};


char *base64_encode(const unsigned char *data,
                    size_t input_length,
                    size_t *output_length) {
    
    *output_length = 4 * ((input_length + 2) / 3);
    
    char *encoded_data = malloc(*output_length + 1);
    if (encoded_data == NULL) return NULL;
    
    for (int i = 0, j = 0; i < input_length;) {
        
        uint32_t octet_a = i < input_length ? data[i++] : 0;
        uint32_t octet_b = i < input_length ? data[i++] : 0;
        uint32_t octet_c = i < input_length ? data[i++] : 0;
        
        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
        
        encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
    }
    
    for (int i = 0; i < mod_table[input_length % 3]; i++)
        encoded_data[*output_length - 1 - i] = '=';
    
    encoded_data[*output_length] = '\0';
    return encoded_data;
}


unsigned char *base64_decode(const char *data,
                             size_t input_length,
                             size_t *output_length) {
    
    if (decoding_table == NULL) build_decoding_table();
    
    if (input_length % 4 != 0) return NULL;
    
    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '=') (*output_length)--;
    if (data[input_length - 2] == '=') (*output_length)--;
    
    unsigned char *decoded_data = malloc(*output_length);
    if (decoded_data == NULL) return NULL;
    
    for (int i = 0, j = 0; i < input_length;) {
        
        uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        
        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);
        
        if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }
    
    return decoded_data;
}


void build_decoding_table() {
    
    decoding_table = malloc(256);
    
    for (int i = 0; i < 64; i++)
        decoding_table[(unsigned char) encoding_table[i]] = i;
}


void base64_cleanup() {
    free(decoding_table);
}

//#pragma mark - c private method
//char *base64_encode(const char* data, int data_len) {
//    //int data_len = strlen(data);
//    int prepare = 0;
//    int ret_len;
//    int temp = 0;
//    char *ret = NULL;
//    char *f = NULL;
//    int tmp = 0;
//    char changed[4];
//    int i = 0;
//    ret_len = data_len / 3;
//    temp = data_len % 3;
//    if (temp > 0) {
//        ret_len += 1;
//    }
//    ret_len = ret_len * 4 + 1;
//    ret = (char *) malloc(ret_len);
//    
//    if (ret == NULL) {
//        printf("No enough memory.\n");
//    }
//    memset(ret, 0, ret_len);
//    f = ret;
//    while (tmp < data_len) {
//        temp = 0;
//        prepare = 0;
//        memset(changed, '\0', 4);
//        while (temp < 3) {
//            //printf("tmp = %d\n", tmp);
//            if (tmp >= data_len) {
//                break;
//            }
//            prepare = ((prepare << 8) | (data[tmp] & 0xFF));
//            tmp++;
//            temp++;
//        }
//        prepare = (prepare << ((3 - temp) * 8));
//        //printf("before for : temp = %d, prepare = %d\n", temp, prepare);
//        for (i = 0; i < 4; i++) {
//            if (temp < i) {
//                changed[i] = 0x40;
//            } else {
//                changed[i] = (prepare >> ((3 - i) * 6)) & 0x3F;
//            }
//            *f = base1[changed[i]];
//            //printf("%.2X", changed[i]);
//            f++;
//        }
//    }
//    *f = '\0';
//    
//    return ret;
//    
//}
///* */
//static char find_pos(char ch) {
//    char *ptr = (char*) strrchr(base1, ch); //the last position (the only) in base[]
//    return (ptr - base1);
//}
///* */
//char *base64_decode(const char *data, int data_len) {
//    int ret_len = (data_len / 4) * 3;
//    int equal_count = 0;
//    char *ret = NULL;
//    char *f = NULL;
//    int tmp = 0;
//    int temp = 0;
//    char need[3];
//    int prepare = 0;
//    int i = 0;
//    if (*(data + data_len - 1) == '=') {
//        equal_count += 1;
//    }
//    if (*(data + data_len - 2) == '=') {
//        equal_count += 1;
//    }
//    if (*(data + data_len - 3) == '=') {	//seems impossible
//        equal_count += 1;
//    }
//    switch (equal_count) {
//        case 0:
//            ret_len += 4;	//3 + 1 [1 for NULL]
//            break;
//        case 1:
//            ret_len += 4;	//Ceil((6*3)/8)+1
//            break;
//        case 2:
//            ret_len += 3;	//Ceil((6*2)/8)+1
//            break;
//        case 3:
//            ret_len += 2;	//Ceil((6*1)/8)+1
//            break;
//    }
//    ret = (char *) malloc(ret_len);
//    if (ret == NULL) {
//        printf("No enough memory.\n");
//    }
//    memset(ret, 0, ret_len);
//    f = ret;
//    while (tmp < (data_len - equal_count)) {
//        temp = 0;
//        prepare = 0;
//        memset(need, 0, 4);
//        while (temp < 4) {
//            if (tmp >= (data_len - equal_count)) {
//                break;
//            }
//            prepare = (prepare << 6) | (find_pos(data[tmp]));
//            temp++;
//            tmp++;
//        }
//        prepare = prepare << ((4 - temp) * 6);
//        for (i = 0; i < 3; i++) {
//            if (i == temp) {
//                break;
//            }
//            *f = (char) ((prepare >> ((2 - i) * 8)) & 0xFF);
//            f++;
//        }
//    }
//    *f = '\0';
//    return ret;
//}